package com.hmjk.health.background.data;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.DatabaseHelper;
import com.hmjk.health.background.NetService;

public class FamilyListUpdated extends DataUpdated{
	private static String TAG = FamilyListUpdated.class.getSimpleName();
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public FamilyListUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
		UPDATE_TIME = 60 * 60 * 1000;
	}

	@Override
	public void setUserData(Object data) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public long delay() {
		long curMs = System.currentTimeMillis();
		long del = curMs - upTime;
		logd("delay curMs="+curMs+" upTime="+upTime+" del="+del);
		if(del >= UPDATE_TIME){
			logd("delay 0");
			return 0;
		}else{
			logd("delay (UPDATE_TIME - del) = "+(UPDATE_TIME - del));
			return (UPDATE_TIME - del);
		}
	}

	private void doRequest(String uid){		
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_FAMILY_LIST);
		si.putExtra("uid", uid);
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_FAMILY_LIST" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}
	
	@Override
	public boolean grab() {
		String uid = mApp.getUID();
		logd("grab uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grab curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > UPDATE_TIME){
			doRequest(uid);
			reqTime = curMs;
			logd("grab req sent!");
			return true;
		}
		return false;
	}

	@Override
	public boolean grabByUser() {
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > MIN_QUERY_DUR * 1000){
			doRequest(uid);
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}

	@Override
	public void receive(String stamp, String sjson) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return;
		
		if(sjson == null)
			return;
		
		if(stamp.startsWith("GET_FAMILY_LIST")){
			boolean update = false;
			try {
				JSONObject json = new JSONObject(sjson);
				int code = json.getInt("code");
				if(code == 200){
					String state = json.getString("state");
					if(state.equalsIgnoreCase("00")){
						JSONObject recdata = json.getJSONObject("recdata");
						if(recdata != null){
							JSONArray array = null;
							dh.clearFalistTable();
							upTime = System.currentTimeMillis();
							
							if(recdata.has("familyarray")){
								array = recdata.getJSONArray("familyarray");
							}
							if((array != null) && (array.length() > 0)){
								for(int index = 0; index < array.length(); index ++){
									JSONObject o = array.getJSONObject(index);
									ContentValues cv = new ContentValues();
									
									String fid = o.getString("fid");
									cv.put(DatabaseHelper.FALIST_FID, fid);
									
									String name = o.getString("familyname");
									cv.put(DatabaseHelper.FALIST_NAME, name);
									String status = "";
									if(o.has("familystatus")){
										status = o.getString("familystatus");
									}
									cv.put(DatabaseHelper.FALIST_STATUS, status);
									
									String build = "0";
									if(o.has("build")){
										build = o.getString("build");
										if(build.equals("0") || build.equals("1")){
											
										}else{
											build = "0";
										}
									}
									cv.put(DatabaseHelper.FALIST_BUILD, build);
									
									String admin = "0";
									if(o.has("admin")){
										admin = o.getString("admin");
										if(admin.equals("0") || admin.equals("1")){
											
										}else{
											admin = "0";
										}
									}
									cv.put(DatabaseHelper.FALIST_ADMIN, admin);
									cv.put(DatabaseHelper.FALIST_TIME, upTime);
									
									dh.addOneItem2FalistTable(cv);
								}
							}
							dh.closeDB();
							update = true;
						}
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
			i.putExtra("type",DataManager.F_FAMILYLIST);
			i.putExtra("state", update);
			mApp.sendBroadcast(i);
		}else if(stamp.startsWith("COMMIT_BUILD_FAMILY")){
			String state = "af";
			int code = 400;
			String fid = "";
			try {
				JSONObject json = new JSONObject(sjson);
				code = json.getInt("code");
				if(code == 200){
					state = json.getString("state");
					if(state.equalsIgnoreCase("00")){
						JSONObject sd = json.getJSONObject("senddata");
						JSONObject rec = json.getJSONObject("recdata");
						if((sd != null) && (rec != null)){
							fid = rec.getString("fid");
							String name = sd.getString("familyname");
							String admin = sd.getString("admin");
							String status = sd.getString("familystatus");
							
							ContentValues cv = new ContentValues();
							cv.put(DatabaseHelper.FALIST_FID, fid);
							cv.put(DatabaseHelper.FALIST_NAME, name);
							cv.put(DatabaseHelper.FALIST_STATUS, status);
							cv.put(DatabaseHelper.FALIST_BUILD, "1");
							cv.put(DatabaseHelper.FALIST_ADMIN, admin);
							upTime = System.currentTimeMillis();
							cv.put(DatabaseHelper.FALIST_TIME, upTime);
							
							dh.addOneItem2FalistTable(cv);
						}
					}
					dh.closeDB();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
			i.putExtra("type",DataManager.F_FAMILYLIST);
			i.putExtra("action", "create");
			i.putExtra("fid", fid);
			i.putExtra("state", state);
			i.putExtra("code", code);
			mApp.sendBroadcast(i);
		}else if(stamp.startsWith("COMMIT_ABORT_BY_MEMBER_FA")){
			String state = "af";
			int code = 400;
			if(sjson != null){
				String checkFid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					if(code == 200){
						state = json.getString("state");
						if(state.equals("00")){
							JSONObject sd = json.getJSONObject("senddata");
							checkFid = sd.getString("fid");
							
							upTime = System.currentTimeMillis();
							dh.deleteOneItemInFalistTable(checkFid);
							
							dh.closeDB();
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_FAMILYLIST);
				i.putExtra("action", "quit");
				i.putExtra("fid", checkFid);
				i.putExtra("state", state);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}
	}

	@Override
	public JSONObject check(String[] arg) {
		JSONObject ret = null;
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return null;
		
		if(arg == null){
			//return all
			Cursor c = dh.queryFalistTableData(null);
			try {
				ret = new JSONObject();
			
				if(c.getCount() > 0){
					JSONArray array = new JSONArray();
					while(c.moveToNext()){
						String fid = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_FID));
						String name = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_NAME));
						String status = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_STATUS));
						String build = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_BUILD));
						String admin = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_ADMIN));
						upTime = c.getLong(c.getColumnIndex(DatabaseHelper.FALIST_TIME));
						JSONObject e = new JSONObject();
						e.put("fid", fid);
						e.put("name", name);
						e.put("status", status);
						e.put("build", build);
						e.put("admin", admin);
						array.put(e);
					}
					ret.put("array", array);
					ret.put("uptime", upTime);
				}else{
					JSONArray array = new JSONArray();
					ret.put("array", array);
					ret.put("uptime", upTime);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				ret = null;
			}
			c.close();
			dh.closeDB();
		}else if(arg[0].equalsIgnoreCase("FID")){
			//return all fid
			Cursor c = dh.queryFalistTableData(DatabaseHelper.FALIST_FID);
			try {
				ret = new JSONObject();
				if(c.getCount() > 0){
					JSONArray array = new JSONArray();
					while(c.moveToNext()){
						String fid = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_FID));
						//upTime = c.getLong(c.getColumnIndex(DatabaseHelper.FALIST_TIME));
						JSONObject e = new JSONObject();
						e.put("fid", fid);
						array.put(e);
					}
					ret.put("array", array);
					//ret.put("uptime", upTime);
				}else{
					JSONArray array = new JSONArray();
					ret.put("array", array);
					//ret.put("uptime", upTime);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				ret = null;
			}
			c.close();
			dh.closeDB();
		}else if(arg[0].length() > 0){
			Cursor c = dh.queryOneFromFalistTable(arg[0]);
			if((c != null) && (c.getCount() > 0)){
				c.moveToFirst();
				try {
					String fid = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_FID));
					String name = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_NAME));
					String status = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_STATUS));
					String build = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_BUILD));
					String admin = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_ADMIN));
					upTime = c.getLong(c.getColumnIndex(DatabaseHelper.FALIST_TIME));
					ret = new JSONObject();
					ret.put("fid", fid);
					ret.put("name", name);
					ret.put("status", status);
					ret.put("build", build);
					ret.put("admin", admin);
					ret.put("uptime", upTime);
				}catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					ret = null;
				}
			}
			if(c != null)
				c.close();
			dh.closeDB();
		}
		
		return ret;
	}
	
	@Override
	public boolean commit(Object data) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return false;
		
		String uid = mApp.getUID();
		
		if((uid == null) || uid.isEmpty())
			return false;
			
		JSONObject json = (JSONObject)data;
		if(json == null)
			return false;
		
		try {
			String act = json.getString("action");
			
			if(act.equalsIgnoreCase("create")){
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				
				si.putExtra("uid", uid);
				Time t = new Time();
				t.setToNow();
				String stamp = null;
				
				si.putExtra("sub_act", NetService.COMMIT_BUILD_FAMILY);
				String name = json.getString("familyname");
				si.putExtra("familyname", name);
				String status = json.getString("familystatus");
				si.putExtra("familystatus", status);
				String admin = json.getString("admin");
				si.putExtra("admin", admin);
				stamp = "COMMIT_BUILD_FAMILY" + t.toString(); 
				si.putExtra("stamp",stamp);
				
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
			}else if(act.equalsIgnoreCase("changename")){
				String fid = json.getString("fid");
				String name = json.getString("name");
								
				Cursor c = dh.queryOneFromFalistTable(fid);
				if((c != null) && (c.getCount() > 0)){
					c.moveToFirst();

					String status = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_STATUS));
					String build = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_BUILD));
					String admin = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_ADMIN));
					upTime = c.getLong(c.getColumnIndex(DatabaseHelper.FALIST_TIME));
					
					ContentValues cv = new ContentValues();

					cv.put(DatabaseHelper.FALIST_FID, fid);
					cv.put(DatabaseHelper.FALIST_NAME, name);
					cv.put(DatabaseHelper.FALIST_STATUS, status);
					cv.put(DatabaseHelper.FALIST_BUILD, build);
					cv.put(DatabaseHelper.FALIST_ADMIN, admin);
					cv.put(DatabaseHelper.FALIST_TIME, upTime);
					dh.updateOneItemInFalistTable(fid, cv);

				}
				if(c != null)
					c.close();
				dh.closeDB();
			}else if(act.equalsIgnoreCase("quit")){
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				
				Time t = new Time();
				t.setToNow();
				String stamp = null;
				si.putExtra("sub_act", NetService.COMMIT_ABORT_BY_MEMBER_FA);
				stamp = "COMMIT_ABORT_BY_MEMBER_FA" + t.toString(); 
				si.putExtra("stamp",stamp);
				si.putExtra("uid", uid);
				String fid = json.getString("fid");
				si.putExtra("fid", fid);
				
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);

			}else if(act.equalsIgnoreCase("set_admin")){
				String fid = json.getString("fid");
				String adminUid = json.getString("adminUid");
				boolean setAdmin = false;
				
				if(mApp.getUID().equals(adminUid)){
					setAdmin = true;
				}
				
				Cursor c = dh.queryOneFromFalistTable(fid);
				if((c != null) && (c.getCount() > 0)){
					c.moveToFirst();

					String cName = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_NAME));
					String cStatus = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_STATUS));
					String cBuild = c.getString(c.getColumnIndex(DatabaseHelper.FALIST_BUILD));
					
					ContentValues cv = new ContentValues();
					
					cv.put(DatabaseHelper.FALIST_FID, fid);
					cv.put(DatabaseHelper.FALIST_NAME, cName);
					cv.put(DatabaseHelper.FALIST_STATUS, cStatus);
					cv.put(DatabaseHelper.FALIST_BUILD, cBuild);
					cv.put(DatabaseHelper.FALIST_ADMIN, setAdmin ? "1" : "0");
					cv.put(DatabaseHelper.FALIST_TIME, upTime);
					dh.updateOneItemInFalistTable(fid, cv);
				}
				if(c != null)
					c.close();
				dh.closeDB();
			}
			
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
